import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {isEmpty, isSuccess} from "@/utils/utils";
import {
  ProFormMoney, ProFormRadio,
  ProFormSelect, ProFormSwitch,
  ProFormText, ProFormTextArea
} from "@ant-design/pro-form";
import styles from './style.less';
import {Card, Col, Form, message, Row, Tree} from "antd";
import {CourseManager, UserManager} from "@/services/api-functions";
import UploadForm from "@/components/UploadForm";
import {CourseMod, CourseModItem, OssPojo} from "@/services/api-types";
// @ts-ignore
import {history} from "umi";
import {SYS_ENUMS} from "@/utils/constants";
import {StepsForm} from "@ant-design/pro-form/es/layouts/StepsForm";
import {FormInstance} from "antd/es";
import Search from "antd/es/input/Search";


export const courseSaveOrUpdate = async (fields: any, select: any, cover: OssPojo|undefined,  detailImage: OssPojo|undefined, courseItems: CourseModItem[]) => {
  try {
    const rpo: CourseMod = {
      id: select?.id ?? '',
      title: fields.title,
      cover,
      detailImage,
      courseItems,
      labelDtoList: fields.labels?.map((name: string)=>{return{id:'', name}}),
      difficulty: fields.difficulty,
      userId: fields.userId,
      folderName: fields.folderName,
      membersFree: fields.membersFree ? 1 : 0,
      originalPrice: fields.originalPrice,
      paymentType: fields.paymentType,
      profile: fields.profile,
      sellingPrice: fields.sellingPrice,
      sellingState: fields.sellingState,
      circleId: fields?.circleId,
    }

    if (isSuccess((select && select.id ? (await CourseManager.courseMod(rpo)) : (await CourseManager.courseAdd(rpo)))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};



const CourseEdit: React.FC<any> = ({match: {params: {id}}}) => {

  const formRef = useRef<FormInstance>();
  const [detailImage, setDetailImage] = useState<OssPojo>();
  const [paymentType, setPaymentType] = useState<'FREE'|'PAY'>("FREE")
  const [course, setCourse] = useState<any>(null);
  const [cover, setCover] = useState<OssPojo>();
  const [current, setCurrent] = useState(0);
  const [courseData, setCourseData] = useState<any>({});
  const [folderName, setFolderName] = useState<string|undefined>(undefined);
  const [chapters, setChapters] = useState<any[]>([]);

  const queryCourseDetail = (id: any) => {
    if (id) {
      CourseManager.detail(id).then(({code, data}) => {
        if (isSuccess(code)) {
          setCourse(data)
          if (data.cover) {
            setCover(data.cover)
          }
          if (data.detailImage) {
            setDetailImage(data.detailImage)
          }
          if(data.folderName){
            setFolderName(data.folderName)
          }
          if(data.paymentType){
            setPaymentType(data.paymentType)
          }
          formRef?.current?.setFieldsValue({
            title: data.title,
            userId: data.userDto?.userId,
            circleId: data.circleId,
            cover: data.cover ? [data.cover] : [],
            detailImage: data.detailImage ? [data.detailImage] : [],
            labels: data?.labelDtoList?.map((label: any) => label?.name) ?? [],
            profile: data.profile,
            difficulty: data.difficulty,
            originalPrice: data.originalPrice,
            sellingPrice: data.sellingPrice,
            paymentType: data.paymentType,
            membersFree: data.membersFree,
          })
        }
      })
    }
  }

  useEffect(() => {
    queryCourseDetail(id)
  }, [id])

  const searchFolder = (name: string) => {
    if(isEmpty(name)){
      message.error("请输入课程文件夹名称")
      return
    }
    CourseManager.folderDetailInfo(name).then(({data, code})=>{
      if (isSuccess(code) && data.length > 0) {
        setChapters(data ?? [])
        setFolderName(name)
      }else{
        message.error("课程文件夹不存在")
      }
    })
  };


  const onFinish = async () => {
    if(isEmpty(folderName)){
      message.error("请输入课程文件夹名称")
      return
    }
    if (await courseSaveOrUpdate({...courseData, folderName, paymentType}, course, cover, detailImage, chapters)) {
      history.push('/course/list')
    }
  };

  const drag = (from: any, to: any) => {
    if (from && to && from?.parentKey === to?.parentKey && from?.key !== to?.key) {
      setChapters(dragDo(chapters, from, to, from.level === 3))
    } else {
      message.error("同级下的课程才可拖拽")
    }
  }

  const dragDo: (arr: any[], fromItem: any, toItem: any, move: boolean) => any[] = (arr: any[], fromItem: any, toItem: any, move: boolean) => {

    if (move) {
      const up = fromItem.sort > toItem.sort, from = up ? toItem.sort : fromItem.sort,
        to = up ? fromItem.sort : toItem.sort, toSort = toItem.sort;
      for (let i = from; i <= to; i++) {
        arr[i].sort = up ? (arr[i].sort + 1) : (arr[i].sort - 1)
      }
      arr[fromItem.sort].sort = toSort;

      arr.sort(((a, b) => a.sort - b.sort))

    } else {
      for (let i = 0; i < arr.length; i++) {
        arr[i].child = dragDo(arr[i].child ?? [], fromItem, toItem, fromItem.parentKey === arr[i].key)
      }
    }
    return [...arr];
  }

  return <PageContainer>
    <Card title={`${id?'编辑':'添加'}课程`} className={styles.card} bordered={false}>
      <StepsForm current={current} onCurrentChange={setCurrent}
                 submitter={{render: (props, dom) => props.step === 2 ? null : dom,}}>
        <StepsForm.StepForm<any>
          formRef={formRef}
          title="设置基本信息"
          initialValues={courseData}
          onFinish={async (values) => {
            setCourseData(values);
            return true;
          }}
          onValuesChange={v => {
            if(v.paymentType){
              setPaymentType(v.paymentType)
            }
          }}
        >
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <ProFormSelect label='课程老师' name='userId' required rules={[{required: true, message: '请设置课程老师',},]}
                             request={async (params) => {
                               const {code, data} = await UserManager.simpleUserQuery({
                                 current: 1,
                                 pageSize: 20,
                                 nickName: params.keyWords ?? '',
                               })
                               return isSuccess(code) ? (data.data ?? []).map((item: any) => {
                                 const {id, nickName, phone} = item
                                 return {label: `${nickName}(${phone ?? '暂无手机号'})`, value: id}
                               }) : []
                             }} showSearch/>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <ProFormText label='课程标题' required rules={[{required: true, message: '请填写标题',},]} name="title"/>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <ProFormSelect label='课程分类' required rules={[{required: true, message: '请填选择课程分类',},]} name='difficulty'
                             initialValue={'START'}
                             options={Object.values(SYS_ENUMS.COURSE_DIFFICULTY)}/>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <ProFormTextArea label='课程描述' required rules={[{required: true, message: '请输入课程描述',},]} name='profile'/>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <ProFormSelect label='标签' name='labels' mode='tags'/>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <UploadForm label='封面' name='cover' type='public' max={1} rules={[{required: true, message: '请上传封面',},]} required={true}
                          accept='.jpg,.jpeg,.bmp,.gif,.png' success={file => setCover(file)}
                          remove={() => setCover(undefined)}/>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <UploadForm label='详情图片' name='detailImage' type='public' max={1} rules={[{required: true, message: '请上传详情图片',},]}
                          required={true} accept='.jpg,.jpeg,.bmp,.gif,.png' success={file => setDetailImage(file)}
                          remove={() => setDetailImage(undefined)}/>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <ProFormRadio.Group label='付费类型' required name="paymentType">
                <ProFormRadio.Button value='FREE'
                                     style={paymentType === 'FREE' ? {backgroundColor: '#40a9ff', color: 'white'} : {}}
                                     onClick={() => setPaymentType('FREE')}>免费</ProFormRadio.Button>
                <ProFormRadio.Button value='PAY'
                                     style={paymentType === 'PAY' ? {backgroundColor: '#40a9ff', color: 'white'} : {}}
                                     onClick={() => setPaymentType('PAY')}>付费</ProFormRadio.Button>
              </ProFormRadio.Group>
            </Col>
          </Row>
          {
            paymentType == 'PAY' && <Row gutter={20}>
              <Col lg={20} md={20} sm={24}>
                <ProFormSwitch label='是否加入会员免费' unCheckedChildren='关闭' checkedChildren='开启' initialValue={false} name='membersFree' required/>
              </Col>
            </Row>
          }

          {
            paymentType == 'PAY' && <Row gutter={20}>
              <Col lg={20} md={20} sm={24}>
                <ProFormMoney label='课程价格' name='sellingPrice' rules={[{required: true, message: '请输入课程价格',},]}/>
              </Col>
            </Row>
          }

          {
            paymentType == 'PAY' && <Row gutter={20}>
              <Col lg={20} md={20} sm={24}>
                <ProFormMoney label='原价' name='originalPrice'/>
              </Col>
            </Row>
          }
        </StepsForm.StepForm>

        <StepsForm.StepForm<any>
          title="设置课程章节"
          onFinish={onFinish}>
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <Form.Item>
                <Search placeholder="请输入课程文件夹名称" onSearch={searchFolder} required/>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col lg={20} md={20} sm={24}>
              <Form.Item label={`所选课程文件夹：${folderName??'请选择'}`}>
                <Tree treeData={chapters}
                      blockNode
                      selectable={false}
                      showLine
                      draggable
                      fieldNames={{title: 'name', key: 'key', children: 'child'}}
                      onDrop={({event, node, dragNode, dragNodesKeys}) => drag(dragNode, node)}
                />
              </Form.Item>
            </Col>
          </Row>
        </StepsForm.StepForm>

      </StepsForm>
    </Card>
  </PageContainer>
};

export default CourseEdit;
